import { constantRoutes } from '@/router/index.js'

import { list2Tree } from "@/utils/index.js"
import Layout from '@/layout'
import RouterView from '@/views/_RouterView'

// 递归毁天灭地
const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    },
    RESET_ROUTES: (state) => {
        console.log('重置路由')
        state = Object.assign(state, {
            routes: [],
            addRoutes: []
        })
    }
}


const actions = {
    generateRoutes({ commit, rootState }, roles) {
        return new Promise(resolve => {

            const { sysMenuVoList } = rootState.user.user;
            let accessedRoutes;

            const menu = list2Tree(sysMenuVoList, 'id', 'parentId', 0)
            
            accessedRoutes = buildRoutes(filterAsyncRoutes(menu)) // 通过filterAsyncRouter过滤掉不合法的路由；最后通过buildRoutes去构造出真正的路由
            commit('SET_ROUTES', accessedRoutes)
            accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
            resolve(accessedRoutes)
        })
    }
}

// 加载视图组件
function loadView(componentUrl) {
    return resolve => require.ensure([], () => resolve(require('@/views' + componentUrl)))
}

// 递归构造路由
function buildRoutes(routes) {
    return routes.map(route => {
        let _route = {};
        let meta = {
            title: route.name,
            icon: route.icon,
        };
        if (route.type == 1) { // 目录
            _route.component = route.parentId == 0 ? Layout : RouterView;
            if (route.children && route.children[0]) {
                _route.redirect = route.children[0].path;
            }
        } else if (route.type == 2) { // 菜单
            _route.component = loadView(route.url)
            meta.actionButtonList = route.children || [];
        }
        return {
            path: route.url,
            name: route.url.slice(1),
            ..._route,
            meta,
            children: route.type == 1 ? buildRoutes(route.children || []) : [], // 只有目录才去在构造children路由
        }
    })
}
// 递归过滤掉有重定向却没有children的父级路由
function filterAsyncRoutes(routes) {
    routes = routes.filter(d => {
        return d.type != 1 || (d.children && d.children.length > 0)
    })
    routes.forEach(route => {
        if (route.children && route.children.length > 0) {
            route.children = filterAsyncRoutes(route.children)
        }
    })
    return routes
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

